package com.xjcs.saplingplan.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.xjcs.saplingplan.R

class GridLineBgView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    //背景颜色
    private var bgColor: Int = R.color.color_bg
        set(value) {
            field = value
            bgPaint.color = value
            invalidate()
        }

    //网格线线宽
    private var lineWidth: Float = 1f
        set(value) {
            field = value
            linePaint.strokeWidth = value
            invalidate()
        }

    //网格线颜色
    private var lineColor: Int = R.color.color_CCCCCC
        set(value) {
            field = value
            linePaint.color = value
            invalidate()
        }

    //列数
    private var columnCount: Int = 0
        set(value) {
            field = value
            invalidate()
        }

    //行数（根据列数和视图尺寸自动计算）
    private var rowCount: Int = 0

    //画笔
    private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }
    private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = 1f
    }

    init {
        val typedArray = context.obtainStyledAttributes(
            attrs,
            R.styleable.GridLineBgView,
            defStyleAttr,
            0
        )
        //默认值
        try {
            bgColor = typedArray.getInt(R.styleable.GridLineBgView_bgColor, R.color.color_bg)
            lineWidth = typedArray.getFloat(R.styleable.GridLineBgView_lineWidth, 1f)
            lineColor = typedArray.getInt(R.styleable.GridLineBgView_lineColor, R.color.color_CCCCCC)
            columnCount = typedArray.getInt(R.styleable.GridLineBgView_columnCount, 20)
        } finally {
            typedArray.recycle()
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //当视图尺寸变化时重新计算行数
        calculateRowCount()
    }

    private fun calculateRowCount() {
        if (columnCount == 0 || height == 0) return

        val cellWidth = width.toFloat() / columnCount
        rowCount = (height / cellWidth).toInt()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //绘制背景
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), bgPaint)

        //如果列数为0，则不会只网格
        if (columnCount == 0) return

        //计算单元格尺寸
        val cellWidth = width.toFloat() / columnCount

        for (i in 0..columnCount) {
            val x = i * cellWidth
            canvas.drawLine(x, 0f, x, height.toFloat(), linePaint)
        }

        //绘制水平线
        for (i in 0..rowCount) {
            val y = i * cellWidth
            canvas.drawLine(0f, y, width.toFloat(), y, linePaint)
        }
    }

}